package thread;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

class Task implements Runnable {

    @Override
    public void run() {
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        System.out.println("执行任务");
    }
}

class Task2 implements Callable<String> {

    @Override
    public String call(){
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        return Thread.currentThread().getName();
    }
}


public class ExecutorTest {


    public static void main(String[] args) throws ExecutionException, InterruptedException, TimeoutException {

        ThreadPoolExecutor executor = new ThreadPoolExecutor(
                2,   //线程池的核心线程数量
                4,             //线程池的最大线程数
                2000,           //当线程数大于核心线程数时，多余的空闲线程存活的最长时间
                TimeUnit.MILLISECONDS,
                new ArrayBlockingQueue<>(5),  //任务队列，用来储存等待执行任务的队列
                Executors.defaultThreadFactory(),       //线程工厂，用来创建线程，一般默认即可
                new ThreadPoolExecutor.DiscardPolicy());  //拒绝策略，当提交的任务过多而不能及时处理时，我们可以定制策略来处理任务
        // 1. 先提交所有任务，不等待
        List<Future<String>> futures = new ArrayList<>();
        for (int i = 0; i < 20; i++) {
            Future<String> future = executor.submit(new Task2());
            futures.add(future);  // 保存 Future，但不 get()
        }

        // 2. 再统一获取结果（此时可以并发执行）
        for (Future<String> future : futures) {
            try {
                System.out.println(future.get(4, TimeUnit.SECONDS));
            } catch (TimeoutException e) {
                System.out.println("任务超时，可能被丢弃");
            } catch (InterruptedException | ExecutionException e) {
                System.out.println("任务执行异常: " + e.getMessage());
            }
        }

        executor.shutdown();
        System.out.println("结束");
    }
}
